package ph.edu.ics.sp.graphisched.gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.plaf.basic.BasicButtonUI;

import ph.edu.ics.sp.graphisched.ClassBox;
import ph.edu.ics.sp.graphisched.PrintToFile;

/**
 * Component to be used as tabComponent; Contains a JLabel to show the text and
 * a JButton to close the tab it belongs to
 */
@SuppressWarnings("serial")
public class ButtonTabComponent extends JPanel {
	private final JTabbedPane pane;
	
	
	public ButtonTabComponent(final JTabbedPane pane,
			final GraphiSchedTablePanel tablePanel) {
		// unset default FlowLayout' gaps
		super(new FlowLayout(FlowLayout.LEFT, 0, 0));
		if (pane == null) {
			throw new NullPointerException("TabbedPane is null");
		}
		this.pane = pane;
		setOpaque(false);

		// make JLabel read titles from JTabbedPane
		JLabel label = new JLabel() {
			public String getText() {
				int i = pane.indexOfTabComponent(ButtonTabComponent.this);
				if (i != -1) {
					return pane.getTitleAt(i);
				}
				return null;
			}
		};

		add(label);
		// add more space between the label and the button
		label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
		// tab button
		JButton button = new TabButton();
		add(button);
		// add more space to the top of the component
		setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
	}
	
	public ButtonTabComponent(final JTabbedPane pane, int i){
		super();
		this.pane = pane;
	}
	
	public ButtonTabComponent(final JTabbedPane pane) {
		// unset default FlowLayout' gaps
		super(new FlowLayout(FlowLayout.LEFT, 0, 0));
		if (pane == null) {
			throw new NullPointerException("TabbedPane is null");
		}
		this.pane = pane;
		setOpaque(false);

		// make JLabel read titles from JTabbedPane
		JLabel label = new JLabel() {
			public String getText() {
				int i = pane.indexOfTabComponent(ButtonTabComponent.this);
				if (i != -1) {
					return pane.getTitleAt(i);
				}
				return null;
			}
		};

		add(label);
		// add more space between the label and the button
		label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
		// tab button
		JButton button = new TabButton();
		add(button);
		// add more space to the top of the component
		setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
	}

	public class TabButton extends JButton implements ActionListener {
		public TabButton() {
			int size = 17;
			setPreferredSize(new Dimension(size, size));
			setToolTipText("close this tab");
			// Make the button looks the same for all Laf's
			setUI(new BasicButtonUI());
			// Make it transparent
			setContentAreaFilled(false);
			// No need to be focusable
			setFocusable(false);
			setBorder(BorderFactory.createEtchedBorder());
			setBorderPainted(false);
			// Making nice rollover effect
			// we use the same listener for all buttons
			addMouseListener(buttonMouseListener);
			setRolloverEnabled(true);
			// Close the proper tab by clicking the button
			addActionListener(this);
		}

		private int getTabIndex(String room) {
			int tabIndex = -1;
			int size = pane.getTabCount();

			for (int i = 0; i < size; i++) {
				if (room.equals(pane.getTitleAt(i))) {
					return i;
				}
			}

			return tabIndex;
		}

		/**
		 * removes lab classes of lecture class to be deleted along with the tab
		 */
		private void removeLabsOnOtherTabs(int tabNumber, String classroomName) {
			TableMatrixPanel tmp = (TableMatrixPanel) pane
					.getComponentAt(tabNumber);
			ArrayList<ClassBox> classes = tmp.getClasses();
			ArrayList<ClassBox> labs = new ArrayList<ClassBox>();
			int size = classes.size();
			for (int i = 0; i < size; i++) {
				ClassBox cb = classes.get(i);
				if (cb.getIsLecture()) {
					labs = cb.getLaboratories();
					if (!labs.isEmpty()) {
						int size2 = labs.size();
						for (int j = 0; j < size2; j++) {
							if (!labs.get(j).getRoom().equals(classroomName)) {
								((TableMatrixPanel) pane
										.getComponentAt(getTabIndex(labs.get(j)
												.getRoom()))).getClasses()
										.remove(labs.get(j));
							}
						}
					}
				} else {
					cb.getLectureClass().removeLab(cb);
				}
			}
		}

		/**
		 * removes tab from tabbedpane and adds classroom name to list of
		 * classroom names
		 */
		public void removeTab(int tabNumber, int option) {
			String classroomName = pane.getTitleAt(tabNumber);
			// remove lab classes on other tabs first before deleting tab
			if (option == JOptionPane.NO_OPTION) {
				removeLabsOnOtherTabs(tabNumber, classroomName);
				int index = GraphiSchedTablePanel.completeClassroomNames
						.indexOf(classroomName);
				GraphiSchedTablePanel.classroomNames.add(index, classroomName);
			}
			// delete tab
			pane.removeTabAt(tabNumber);
		}

		/**
		 * gets the lecture sessions of the selected course in the course list
		 */
		public ArrayList<ClassBox> getCourseLectures(String courseCode) {
			ArrayList<ClassBox> lectures = new ArrayList<ClassBox>();
			// get from opened tabs
			int size = pane.getTabCount();
			for (int i = 0; i < size; i++) {
				TableMatrixPanel tmp = (TableMatrixPanel) pane
						.getComponentAt(i);
				int classSize = tmp.getClasses().size();
				for (int j = 0; j < classSize; j++) {
					ClassBox cb = tmp.getClasses().get(j);
					if (cb.getSubject().getCourseCode().equals(courseCode)
							&& cb.getIsLecture()) {
						lectures.add(tmp.getClasses().get(j));
					}
				}
			}
			// get from closed tabs
			int size2 = GraphiSchedTablePanel.storedTabs.size();
			for (int i = 0; i < size2; i++) {
				TableMatrixPanel tmp = GraphiSchedTablePanel.storedTabs.get(i);
				int classSize = tmp.getClasses().size();
				for (int j = 0; j < classSize; j++) {
					ClassBox cb = tmp.getClasses().get(j);
					if (cb.getSubject().getCourseCode().equals(courseCode)
							&& cb.getIsLecture()) {
						lectures.add(tmp.getClasses().get(j));
					}
				}
			}
			lectures = new PrintToFile().sortLectures(lectures);
			return lectures;
		}

		/**
		 * tab close button action listener
		 */
		public void actionPerformed(ActionEvent e) {
			int i = pane.indexOfTabComponent(ButtonTabComponent.this);
			if (i != -1) {
				if (((TableMatrixPanel) pane.getComponentAt(i)).getClasses()
						.size() != 0) {
					StringBuffer ques = new StringBuffer();
					ques
							.append("There are data stored on this tab.\nDo you want to keep this tab?");
					int returnVal = JOptionPane.showConfirmDialog(null, ques,
							"Confirm Delete", JOptionPane.YES_NO_CANCEL_OPTION,
							JOptionPane.QUESTION_MESSAGE, null);
					if (returnVal == JOptionPane.YES_OPTION) {
						GraphiSchedTablePanel.storedTabs
								.add((TableMatrixPanel) pane.getComponentAt(i));
						GraphiSchedTablePanel.storedTabsListModel
								.addElement(((TableMatrixPanel) pane
										.getComponentAt(i)).getRoom());
						removeTab(i, returnVal);
					} else if (returnVal == JOptionPane.NO_OPTION) {
						ArrayList<ClassBox> toBeRemovedClasses = ((TableMatrixPanel) pane
								.getComponentAt(i)).getClasses();
						removeTab(i, returnVal);
						int size = toBeRemovedClasses.size();
						for (int j = 0; j < size; j++) {
							ClassBox cb = toBeRemovedClasses.get(j);

							GraphiSchedTablePanel.treePanel.removeClass(cb,
									getCourseLectures(cb.getSubject()
											.getCourseCode()));
						}
					}
				} else {
					removeTab(i, JOptionPane.NO_OPTION);
				}

			}
		}

		// we don't want to update UI for this button
		public void updateUI() {
		}

		// paint the cross
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			Graphics2D g2 = (Graphics2D) g.create();
			// shift the image for pressed buttons
			if (getModel().isPressed()) {
				g2.translate(1, 1);
			}
			g2.setStroke(new BasicStroke(2));
			g2.setColor(Color.BLACK);
			if (getModel().isRollover()) {
				g2.setColor(Color.MAGENTA);
			}
			int delta = 6;
			g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight()
					- delta - 1);
			g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight()
					- delta - 1);
			g2.dispose();
		}
	}

	private final static MouseListener buttonMouseListener = new MouseAdapter() {
		public void mouseEntered(MouseEvent e) {
			Component component = e.getComponent();
			if (component instanceof AbstractButton) {
				AbstractButton button = (AbstractButton) component;
				button.setBorderPainted(true);
			}
		}

		public void mouseExited(MouseEvent e) {
			Component component = e.getComponent();
			if (component instanceof AbstractButton) {
				AbstractButton button = (AbstractButton) component;
				button.setBorderPainted(false);
			}
		}
	};
}
